import axios from 'axios'
import { getAntvNode } from '/@/api/antvx6'

// 参数组配置类型定义
export interface ParameterGroup {
  key: string
  title: string
  collapsed?: boolean
}

// 节点属性配置类型定义 - 从nodeProperties.ts迁移
export interface NodeProperty {
  key: string
  label: string
  type: 'input' | 'select' | 'number' | 'color' | 'switch' | 'textarea'
  group?: string // 属性所属的参数组
  defaultValue: any
  options?: { label: string; value: any }[]
  min?: number
  max?: number
  step?: number
  placeholder?: string
  required?: boolean
  description?: string // 添加描述字段，用于气泡提示
  // SVG文本更新相关配置
  svgTextTarget?: boolean // 标记是否会更新SVG文本
  svgTextSelector?: string // SVG中的文本选择器
  svgTextFormat?: (value: any) => string // 文本格式化函数
}

export interface NodePin {
  id: string
  label: string
  position: 'left' | 'right' | 'top' | 'bottom'
  type: 'input' | 'output'
  defaultValue?: string
  isDynamic?: boolean
  index?: number
}

// 动态引脚配置接口
export interface DynamicPinConfig {
  portId: string
  portGroup?: string
  portPosition?: { x: number; y: number }
  portType: 'input' | 'output'
  portLabel?: string
}

export interface NodeConfiguration {
  nodeType: string
  name: string
  category: string
  properties: NodeProperty[]
  pins: NodePin[]
  parameterGroups?: ParameterGroup[] // 参数组配置
  supportsDynamicPins?: boolean
  isModule?: boolean // 标记是否为模块节点
  dynamicPinConfig?: {
    enabledPositions: ('left' | 'right' | 'top' | 'bottom')[]
    defaultPinType: 'input' | 'output'
    autoLabelGeneration: boolean
  }
}

// 节点注册配置接口 - 继承自NodeConfiguration
export interface NodeRegistration extends NodeConfiguration {
  // 节点外观与结构配置
  shape: {
    inherit: string // 继承自哪种基础形状
    width: number
    height: number
    markup?: any[] // 节点的SVG标记结构
    attrs: {
      // 节点的样式属性
      body?: any
      image?: any
      text?: any
      label?: any
      title?: any
      [key: string]: any // 其他可能的属性
    }
  }
  // 端口配置（连接桩）
  ports: {
    groups: {
      [key: string]: {
        position: string | { name: string }
        attrs: {
          circle?: any
          text?: any
          [key: string]: any
        }
        label?: {
          position: string
        }
      }
    }
    items: Array<{
      group: string
      id: string
      args?: any
      attrs?: any
      [key: string]: any
    }>
  }
  // 工具配置
  tools?: Array<{
    name: string
    args?: any
  }>
}

// Stencil组配置接口
export interface StencilGroupConfig {
  name: string
  title: string
  graphHeight?: number
}

// Stencil节点实例配置接口
export interface StencilNodeInstance {
  id: string
  label?: string
  attrs?: any
}

// 动态节点信息管理器
export interface NodeRegistrationJSON {
  nodeType: string
  name: string
  category: string
  stencilGroup: string
  stencilConfig?: StencilNodeInstance[]
  shape: {
    inherit: string
    width: number
    height: number
    attrs: any
    markup?: any[]
  }
  ports: any
  tools?: any[]
  supportsDynamicPins?: boolean
  dynamicPinConfig?: any
  parameterGroups?: ParameterGroup[] // 添加参数组配置字段
  properties: Array<{
    key: string
    label: string
    type: string
    group?: string // 添加属性分组字段
    defaultValue: any
    min?: number
    max?: number
    step?: number
    placeholder?: string
    description?: string
    svgTextTarget?: boolean
    svgTextSelector?: string
    svgTextFormat?: string
    options?: any[]
  }>
  pins: any[]
}

export interface NodeRegistrationsData {
  stencilGroups: StencilGroupConfig[]
  nodeRegistrations: NodeRegistrationJSON[]
}

// 从数据源加载节点配置 - 支持JSON文件和远程API
export async function loadNodeRegistrationsFromJSON(dataSource?: string | (() => Promise<NodeRegistrationsData>)): Promise<{
  stencilGroups: StencilGroupConfig[]
  nodeRegistrations: NodeRegistrationJSON[]
}> {
  try {
    let data: NodeRegistrationsData

    if (typeof dataSource === 'function') {
      // 从函数获取数据（例如API调用）
      data = await dataSource()
    } else if (typeof dataSource === 'string') {
      // const response = await fetch(dataSource)
      // if (!response.ok) {
      //   throw new Error(`HTTP error! status: ${response.status}`)
      // }
      // data = await response.json()
      // 从指定URL获取数据
      const response = await axios.get(dataSource)
      data = response.data
    } else {
      // 默认从本地JSON文件获取数据（public目录）
      // const response = await fetch('/nodeProperties.json')
      // if (!response.ok) {
      //   throw new Error(`HTTP error! status: ${response.status}`)
      // }
      // data = await response.json()

      // 使用import方式（备用方案）
      // const nodePropertiesModule = await import('../mockData/nodeProperties.json')
      // data = nodePropertiesModule.default || nodePropertiesModule
      // 默认从API获取数据（已注释）
      // const response = await axios.get('http://127.0.0.1:8000/node-properties')
      const response = await getAntvNode()
      data = response.data || response
    }

    return {
      stencilGroups: data.stencilGroups || [],
      nodeRegistrations: data.nodeRegistrations || [],
    }
  } catch (error) {
    console.error('加载节点配置失败:', error)
    return {
      stencilGroups: [],
      nodeRegistrations: [],
    }
  }
}

// 动态注册节点到Graph
export function registerNodesFromJSON(GraphConstructor: any, nodeRegistrations: NodeRegistrationJSON[]) {
  nodeRegistrations.forEach((nodeReg) => {
    try {
      // 为每个节点创建唯一的端口ID，避免重复
      const clonedNodeReg = JSON.parse(JSON.stringify(nodeReg)) // 深拷贝以避免修改原始数据

      if (clonedNodeReg.ports && clonedNodeReg.ports.items) {
        clonedNodeReg.ports.items = clonedNodeReg.ports.items.map((item: any, index: number) => ({
          ...item,
          id: `${clonedNodeReg.nodeType}-${item.id || `port-${index}`}` // 使用节点类型作为前缀确保唯一性
        }))
      }

      GraphConstructor.registerNode(
        clonedNodeReg.nodeType,
        {
          inherit: clonedNodeReg.shape.inherit,
          width: clonedNodeReg.shape.width,
          height: clonedNodeReg.shape.height,
          attrs: clonedNodeReg.shape.attrs,
          markup: clonedNodeReg.shape.markup,
          ports: clonedNodeReg.ports,
          tools: clonedNodeReg.tools,
        },
        true
      )

      // console.log(`成功注册节点: ${clonedNodeReg.nodeType} - ${clonedNodeReg.name}`)
    } catch (error) {
      console.error(`注册节点失败: ${nodeReg.nodeType}`, error)
    }
  })
}

// 获取节点配置信息
export function getNodeConfigurationFromJSON(nodeType: string, nodeRegistrations: NodeRegistrationJSON[]): NodeRegistrationJSON | null {
  return nodeRegistrations.find((reg) => reg.nodeType === nodeType) || null
}

// 获取所有节点类型
export function getNodeTypesFromJSON(nodeRegistrations: NodeRegistrationJSON[]): string[] {
  return nodeRegistrations.map((reg) => reg.nodeType)
}

// 获取所有节点分类
export function getNodeCategoriesFromJSON(nodeRegistrations: NodeRegistrationJSON[]): string[] {
  const categories = new Set(nodeRegistrations.map((reg) => reg.category))
  return Array.from(categories)
}

// 创建可拖拽的节点实例 - 完全基于JSON配置，无硬编码
export function createDraggableNode(graph: any, nodeType: string, nodeRegistrations: NodeRegistrationJSON[]): any {
  const nodeConfig = getNodeConfigurationFromJSON(nodeType, nodeRegistrations)
  if (!nodeConfig) {
    console.warn(`找不到节点配置: ${nodeType}`)
    return null
  }

  // 基础节点创建配置
  const baseNodeConfig: any = {
    shape: nodeType,
  }

  // 从JSON配置中获取attrs
  if (nodeConfig.shape.attrs) {
    baseNodeConfig.attrs = { ...nodeConfig.shape.attrs }
  }

  // 如果是基本形状节点且有默认标签，添加标签
  const basicShapes = ['custom-rect', 'custom-circle', 'custom-polygon']
  if (basicShapes.includes(nodeType)) {
    baseNodeConfig.label = nodeConfig.name
  }

  // 为image类型节点处理图片
  if (nodeConfig.shape.attrs?.image?.['xlink:href']) {
    if (!baseNodeConfig.attrs) baseNodeConfig.attrs = {}
    if (!baseNodeConfig.attrs.image) baseNodeConfig.attrs.image = {}
    baseNodeConfig.attrs.image['xlink:href'] = nodeConfig.shape.attrs.image['xlink:href']
  }

  // 保存原始SVG路径和默认属性到节点数据中，用于SVG文本更新
  const nodeData: any = {
    nodeType,
    nodeConfig,
  }

  // 保存原始SVG路径
  if (nodeConfig.shape.attrs?.image?.['xlink:href']) {
    nodeData.originalSvgPath = nodeConfig.shape.attrs.image['xlink:href']
  }

  // 保存默认属性值
  const defaultProperties: Record<string, any> = {}
  nodeConfig.properties.forEach((prop) => {
    if (prop.defaultValue !== undefined && prop.defaultValue !== null) {
      defaultProperties[prop.key] = prop.defaultValue
    }
  })
  nodeData.properties = defaultProperties

  baseNodeConfig.data = nodeData

  console.log(`创建可拖拽节点: ${nodeType}`, baseNodeConfig)
  return graph.createNode(baseNodeConfig)
}

// 示例：从远程API获取节点配置
export async function loadNodeRegistrationsFromAPI(apiEndpoint: string = '/api/node-configurations'): Promise<NodeRegistrationsData> {
  const response = await fetch(apiEndpoint, {
    method: 'GET',
    headers: {
      'Content-Type': 'application/json',
      // 可以添加认证头
      // 'Authorization': `Bearer ${getAuthToken()}`
    },
  })

  if (!response.ok) {
    throw new Error(`API调用失败: ${response.status} ${response.statusText}`)
  }

  return await response.json()
}

// 缓存机制
let cachedNodeData: NodeRegistrationsData | null = null
let cacheTimestamp: number = 0
const CACHE_DURATION = 5 * 60 * 1000 // 5分钟缓存

export async function loadNodeRegistrationsWithCache(
  dataSource?: string | (() => Promise<NodeRegistrationsData>),
  useCache: boolean = true
): Promise<{
  stencilGroups: StencilGroupConfig[]
  nodeRegistrations: NodeRegistrationJSON[]
}> {
  // 检查缓存
  if (useCache && cachedNodeData && Date.now() - cacheTimestamp < CACHE_DURATION) {
    return {
      stencilGroups: cachedNodeData.stencilGroups || [],
      nodeRegistrations: cachedNodeData.nodeRegistrations || [],
    }
  }

  // 加载新数据
  const result = await loadNodeRegistrationsFromJSON(dataSource)

  // 更新缓存
  if (useCache) {
    cachedNodeData = {
      stencilGroups: result.stencilGroups,
      nodeRegistrations: result.nodeRegistrations,
    }
    cacheTimestamp = Date.now()
  }

  return result
}

// 清除缓存
export function clearNodeConfigCache(): void {
  cachedNodeData = null
  cacheTimestamp = 0
  // console.log('节点配置缓存已清除')
}

// 更新SVG文本内容的函数
export function updateSVGTextContent(node: any, propertyKey: string, value: any, nodeRegistrations: NodeRegistrationJSON[]): void {
  const nodeConfig = getNodeConfigurationFromJSON(node.shape, nodeRegistrations)
  if (!nodeConfig) return

  const property = nodeConfig.properties.find((p) => p.key === propertyKey && p.svgTextTarget)
  if (!property || !property.svgTextSelector) return

  // 使用格式化函数
  let formattedText = value
  if (property.svgTextFormat && typeof property.svgTextFormat === 'string') {
    // 动态执行字符串表达式
    try {
      const formatFunc = new Function('value', `return ${property.svgTextFormat}`)
      formattedText = formatFunc(value)
    } catch {
      // console.error('SVG文本格式化失败:', error)
      formattedText = value
    }
  }

  console.log(`更新SVG文本: ${propertyKey} = ${formattedText}`)

  // 这里可以调用实际的SVG更新逻辑
  // 例如调用现有的updateSVGNodeText函数
}

// ==================== 从nodeProperties.ts迁移的实用函数 ====================

// 根据节点类型获取配置 - 兼容原有功能
export function getNodeConfiguration(nodeType: string, nodeRegistrations?: NodeRegistrationJSON[]): NodeConfiguration | null {
  // 如果没有提供nodeRegistrations，尝试使用缓存
  if (!nodeRegistrations && cachedNodeData) {
    nodeRegistrations = cachedNodeData.nodeRegistrations
  }

  if (!nodeRegistrations) {
    // console.warn('getNodeConfiguration: 没有可用的节点注册数据')
    return null
  }

  const nodeConfig = getNodeConfigurationFromJSON(nodeType, nodeRegistrations)
  if (!nodeConfig) return null

  // 转换为兼容的NodeConfiguration格式
  return {
    nodeType: nodeConfig.nodeType,
    name: nodeConfig.name,
    category: nodeConfig.category,
    properties: nodeConfig.properties as NodeProperty[],
    pins: nodeConfig.pins as NodePin[],
    parameterGroups: nodeConfig.parameterGroups, // 添加缺失的参数组配置
    supportsDynamicPins: nodeConfig.supportsDynamicPins,
    dynamicPinConfig: nodeConfig.dynamicPinConfig,
  }
}

// 获取所有节点类型 - 兼容原有功能
export function getNodeTypes(nodeRegistrations?: NodeRegistrationJSON[]): string[] {
  if (!nodeRegistrations && cachedNodeData) {
    nodeRegistrations = cachedNodeData.nodeRegistrations
  }

  if (!nodeRegistrations) {
    return []
  }

  return getNodeTypesFromJSON(nodeRegistrations)
}

// 获取节点类别 - 兼容原有功能
export function getNodeCategories(nodeRegistrations?: NodeRegistrationJSON[]): string[] {
  if (!nodeRegistrations && cachedNodeData) {
    nodeRegistrations = cachedNodeData.nodeRegistrations
  }

  if (!nodeRegistrations) {
    return []
  }

  return getNodeCategoriesFromJSON(nodeRegistrations)
}

// 获取节点注册信息 - 兼容原有功能
export function getNodeRegistration(nodeType: string, nodeRegistrations?: NodeRegistrationJSON[]): NodeRegistration | null {
  if (!nodeRegistrations && cachedNodeData) {
    nodeRegistrations = cachedNodeData.nodeRegistrations
  }

  if (!nodeRegistrations) {
    return null
  }

  const nodeConfig = getNodeConfigurationFromJSON(nodeType, nodeRegistrations)
  if (!nodeConfig) return null

  // 转换为兼容的NodeRegistration格式
  return {
    ...nodeConfig,
    properties: nodeConfig.properties as NodeProperty[],
    pins: nodeConfig.pins as NodePin[],
  } as NodeRegistration
}

// 动态生成引脚配置的函数
export function generateDynamicPins(ports: DynamicPinConfig[]): NodePin[] {
  const dynamicPins: NodePin[] = []

  ports.forEach((port, index) => {
    // 判断引脚位置，left和top为输入，right和bottom为输出
    const position = getPortPosition(port.portGroup, port.portPosition)
    const type = position === 'left' || position === 'top' ? 'input' : 'output'

    dynamicPins.push({
      id: port.portId,
      label: port.portLabel || `引脚${index + 1}`,
      position,
      type,
      defaultValue: '', // 初始化为空
      isDynamic: true,
      index,
    })
  })

  return dynamicPins
}

// 辅助函数：根据端口组和位置确定引脚位置
function getPortPosition(group?: string, position?: { x: number; y: number }): 'left' | 'right' | 'top' | 'bottom' {
  if (
    group && // 如果有端口组信息，直接使用
    ['left', 'right', 'top', 'bottom'].includes(group)
  ) {
    return group as 'left' | 'right' | 'top' | 'bottom'
  }

  // 如果没有组信息，根据位置坐标推断
  if (position) {
    // 这里可以根据实际需求调整判断逻辑
    if (position.x <= 20) return 'left'
    if (position.y <= 20) return 'top'
    return 'right' // 默认为右侧
  }

  return 'right' // 默认为右侧输出
}

// 从AntV X6节点生成动态引脚配置
export function generatePinsFromNode(node: any): NodePin[] {
  const dynamicPins: NodePin[] = []

  // 检查节点是否有ports配置
  const ports = node.getPorts ? node.getPorts() : []

  if (ports && ports.length > 0) {
    // 基于实际的ports生成引脚配置
    ports.forEach((port: any, index: number) => {
      const portId = port.id || `port_${index}`
      const portGroup = node.getPortProp ? node.getPortProp(portId, 'group') : 'right'

      // 判断引脚位置和类型
      const position = getPortPositionFromGroup(portGroup)
      const type = position === 'left' || position === 'top' ? 'input' : 'output'

      dynamicPins.push({
        id: portId,
        label: `引脚${index + 1}`,
        position,
        type,
        defaultValue: '', // 初始化为空
        isDynamic: true,
        index,
      })
    })
  } else {
    // 如果节点没有ports，根据节点形状生成默认引脚
    const nodeShape = node.shape || 'rect'
    const defaultPins = getDefaultPinsByShape(nodeShape)
    dynamicPins.push(...defaultPins)
  }

  return dynamicPins
}

// 辅助函数：根据端口组名称确定引脚位置
function getPortPositionFromGroup(group: string): 'left' | 'right' | 'top' | 'bottom' {
  const groupLower = group.toLowerCase()

  if (groupLower.includes('left')) return 'left'
  if (groupLower.includes('right')) return 'right'
  if (groupLower.includes('top')) return 'top'
  if (groupLower.includes('bottom')) return 'bottom'

  // 对于自定义端口组，默认为右侧
  return 'right'
}

// 辅助函数：根据节点形状生成默认引脚
function getDefaultPinsByShape(shape: string): NodePin[] {
  const pins: NodePin[] = []

  switch (shape) {
    case 'rect':
    case 'circle':
    case 'ellipse': {
      // 基础形状：左右两个引脚
      pins.push(
        {
          id: 'port_left',
          label: '引脚1',
          position: 'left',
          type: 'input',
          defaultValue: '',
          isDynamic: true,
          index: 0,
        },
        {
          id: 'port_right',
          label: '引脚2',
          position: 'right',
          type: 'output',
          defaultValue: '',
          isDynamic: true,
          index: 1,
        }
      )
      break
    }

    case 'polygon': {
      // 多边形：四个引脚
      pins.push(
        {
          id: 'port_left',
          label: '引脚1',
          position: 'left',
          type: 'input',
          defaultValue: '',
          isDynamic: true,
          index: 0,
        },
        {
          id: 'port_top',
          label: '引脚2',
          position: 'top',
          type: 'input',
          defaultValue: '',
          isDynamic: true,
          index: 1,
        },
        {
          id: 'port_right',
          label: '引脚3',
          position: 'right',
          type: 'output',
          defaultValue: '',
          isDynamic: true,
          index: 2,
        },
        {
          id: 'port_bottom',
          label: '引脚4',
          position: 'bottom',
          type: 'output',
          defaultValue: '',
          isDynamic: true,
          index: 3,
        }
      )
      break
    }

    default: {
      // 其他类型：默认两个引脚
      pins.push(
        {
          id: 'port_input',
          label: '引脚1',
          position: 'left',
          type: 'input',
          defaultValue: '',
          isDynamic: true,
          index: 0,
        },
        {
          id: 'port_output',
          label: '引脚2',
          position: 'right',
          type: 'output',
          defaultValue: '',
          isDynamic: true,
          index: 1,
        }
      )
      break
    }
  }

  return pins
}

// 获取或创建动态节点配置
export function getOrCreateDynamicNodeConfiguration(node: any, nodeRegistrations?: NodeRegistrationJSON[]): NodeConfiguration {
  // 首先尝试获取已有配置
  let config = getNodeConfiguration(node.shape || node.nodeType, nodeRegistrations)

  if (!config) {
    // 如果没有配置，创建一个基础配置
    config = {
      nodeType: node.shape || 'unknown',
      name: node.shape || 'Unknown Node',
      category: '基础形状',
      supportsDynamicPins: true,
      dynamicPinConfig: {
        enabledPositions: ['left', 'right', 'top', 'bottom'],
        defaultPinType: 'input',
        autoLabelGeneration: true,
      },
      properties: [
        {
          key: 'name',
          label: '节点名称',
          type: 'input',
          defaultValue: '',
          placeholder: '请输入节点名称',
          required: true,
        },
        {
          key: 'enabled',
          label: '启用',
          type: 'switch',
          defaultValue: true,
        },
      ],
      pins: [],
    }
  }

  // 生成动态引脚配置
  if (config.supportsDynamicPins) {
    config.pins = generatePinsFromNode(node)
  }

  return config
}

// 注册节点到Graph - 兼容原有功能
export function registerNodes(Graph: any, nodeRegistrations?: NodeRegistrationJSON[]) {
  if (!nodeRegistrations && cachedNodeData) {
    nodeRegistrations = cachedNodeData.nodeRegistrations
  }

  if (!nodeRegistrations) {
    console.warn('registerNodes: 没有可用的节点注册数据')
    return false
  }

  return registerNodesFromJSON(Graph, nodeRegistrations)
}
